package com.mcc.system.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mcc.system.mapper.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.mcc.common.core.domain.entity.SysRole;
import com.mcc.common.exception.CustomException;
import com.mcc.common.utils.StringUtils;
import com.mcc.system.domain.SysRoleMenu;
import com.mcc.system.mapper.SysRoleMapper;
import com.mcc.system.mapper.SysRoleMenuMapper;
import com.mcc.system.service.ISysRoleService;

/**
 * 角色 业务层处理
 *
 * @author gxy
 */
@Service
public class SysRoleServiceImpl implements ISysRoleService {

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysRoleMenuMapper roleMenuMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    /**
     * 根据条件分页查询角色数据
     *
     * @param role 角色信息
     * @return 角色数据集合信息
     */
    @Override
    public List<SysRole> selectRoleList(SysRole role) {
        QueryWrapper queryWrapper = new QueryWrapper();
        if (ObjectUtil.isNotEmpty(role)) {
            queryWrapper.like(ObjectUtil.isNotEmpty(role.getRoleKey()), "role_key", role.getRoleKey());
            queryWrapper.like(ObjectUtil.isNotEmpty(role.getRoleName()), "role_name", role.getRoleName());
            queryWrapper.eq(ObjectUtil.isNotEmpty(role.getStatus()), "status", role.getStatus());
            queryWrapper.ge(ObjectUtil.isNotEmpty(role.getBeginTime()), "date_format(create_time,'%Y-%m-%d')", role.getBeginTime());
            queryWrapper.le(ObjectUtil.isNotEmpty(role.getEndTime()), "date_format(create_time,'%Y-%m-%d')", role.getEndTime());
        }
        queryWrapper.orderByAsc("role_sort");
        return roleMapper.selectList(queryWrapper);
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectRolePermissionByUserId(Long userId) {
        Set<String> permsSet = new HashSet<>();
        QueryWrapper userWrapper = new QueryWrapper();
        userWrapper.eq("user_id", userId);
        userWrapper.select("role_id");
        List<Long> roleIds = userRoleMapper.selectObjs(userWrapper);
        if (roleIds.size() > 0) {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.in("role_id", roleIds);
            List<SysRole> perms = roleMapper.selectList(queryWrapper);
            for (SysRole perm : perms) {
                if (StringUtils.isNotNull(perm)) {
                    permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
                }
            }
        }
        return permsSet;
    }

    /**
     * 根据用户ID获取角色选择框列表
     *
     * @param userId 用户ID
     * @return 选中角色ID列表
     */
    @Override
    public List<Long> selectRoleObjsByUserId(Long userId) {
        QueryWrapper userWrapper = new QueryWrapper();
        userWrapper.eq("user_id", userId);
        userWrapper.select("role_id");
        return userRoleMapper.selectObjs(userWrapper);
    }

    /**
     * 通过角色ID查询角色
     *
     * @param roleId 角色ID
     * @return 角色对象信息
     */
    @Override
    public SysRole selectRoleById(Long roleId) {
        return roleMapper.selectById(roleId);
    }

    /**
     * 校验角色名称是否唯一
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public boolean checkRoleNameUnique(SysRole role) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("role_name", role.getRoleName());
        queryWrapper.ne(ObjectUtil.isNotEmpty(role.getRoleId()), "role_id", role.getRoleId());
        return roleMapper.selectCount(queryWrapper) == 0;
    }

    /**
     * 校验角色权限是否唯一
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public boolean checkRoleKeyUnique(SysRole role) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("role_key", role.getRoleKey());
        queryWrapper.ne(ObjectUtil.isNotEmpty(role.getRoleId()), "role_id", role.getRoleId());
        return roleMapper.selectCount(queryWrapper) == 0;
    }

    /**
     * 新增角色信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertRole(SysRole role) {
        // 新增角色信息
        int res = roleMapper.insert(role);
        if (res > 0) {
            insertRoleMenu(role);
        }
        return res;
    }

    /**
     * 修改角色信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateRole(SysRole role) {
        // 修改角色信息
        int res = roleMapper.updateById(role);
        if (res > 0) {
            // 删除角色与菜单关联
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("role_id", role.getRoleId());
            roleMenuMapper.delete(queryWrapper);
            insertRoleMenu(role);
        }
        return res;
    }

    /**
     * 新增角色菜单信息
     *
     * @param role 角色对象
     */
    public void insertRoleMenu(SysRole role) {
        // 新增用户与角色管理
        List<SysRoleMenu> list = new ArrayList<>();
        for (Long menuId : role.getMenuIds()) {
            SysRoleMenu rm = new SysRoleMenu();
            rm.setRoleId(role.getRoleId());
            rm.setMenuId(menuId);
            list.add(rm);
        }
        if (list.size() > 0) {
            roleMenuMapper.batchRoleMenu(list);
        }
    }

    /**
     * 通过角色ID删除角色
     *
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    public int deleteRoleById(Long roleId) {
        int res = roleMapper.deleteById(roleId);
        if (res > 0) {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("role_id", roleId);
            roleMenuMapper.delete(queryWrapper);
        }
        return res;
    }

    /**
     * 批量删除角色信息
     *
     * @param roleIds 需要删除的角色ID
     * @return 结果
     */
    @Override
    public int deleteRoleByIds(Long[] roleIds) {
        if (roleIds.length == 0) return 0;
        int res = roleMapper.deleteBatchIds(ListUtil.toList(roleIds));
        if (res > 0) {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.in("role_id", roleIds);
            roleMenuMapper.delete(queryWrapper);
        }
        return res;
    }

    @Override
    public List<SysRole> selectRoleListByUserId(Long userId) {
        List<Long> roleIds = selectRoleObjsByUserId(userId);
        if (roleIds.size() == 0) return new ArrayList<>();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("role_id", roleIds);
        return roleMapper.selectList(queryWrapper);
    }
}
